package com.example.aboutwork.synckeyword;

import lombok.Getter;
import lombok.SneakyThrows;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Getter
public class SyncThisUse {


    final Object lock = new Object();
    int num = 0;

    public void incr() {
        for (; ; ) {
            synchronized (this) {
                System.out.println("incr*******" +Thread.currentThread().getName()+"****");
                num++;
                System.err.println(num);
                if (num > 5) {
                    return;
                }
            }
        }


    }

    public void incr1() {
        for (; ; ) {
            synchronized (lock) {
                System.err.println("incr1*********"+Thread.currentThread().getName());
                num++;
                System.err.println(num);
                if (num > 5) {
                    return;
                }
            }
        }


    }

    @SneakyThrows
    @Test
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        int size = Runtime.getRuntime().availableProcessors();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        SyncThisUse syncThisUse = new SyncThisUse();
        for (int i = 0; i < size; i++) {
            executorService.execute(() -> {
                syncThisUse.incr1();
                syncThisUse.incr();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();

    }


    /*
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-2
pool-1-thread-6


pool-1-thread-1
1
pool-1-thread-1
2
pool-1-thread-1
3
pool-1-thread-1
4
pool-1-thread-1
5
pool-1-thread-1
6
pool-1-thread-3
7
pool-1-thread-4
8
pool-1-thread-2
9
pool-1-thread-5
10
pool-1-thread-6
11


     */


    @SneakyThrows
    @Test
    public void test() {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        int size = Runtime.getRuntime().availableProcessors();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        SyncThisUse syncThisUse = new SyncThisUse();
        for (int i = 0; i < size; i++) {
            executorService.execute(() -> {
                syncThisUse.incr1();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

}
